import _ from "lodash";

function getUrlMap(key){
    let map = getUrlMap.map;
    let getResult = (list,parent,crumbs)=>{

        list.map((v)=>{
            let parentNode =  parent || v;
            let crumbsNode = crumbs?[...crumbs]:[];
            let arr = (v.url||'').split('/');
            let cateSlug = arr.pop();
            let type = arr.pop();
            if("group" == type){
                map[v.url] = {
                    type:type,
                    cate:cateSlug.split("$"),
                    menu:parentNode,
                    menuItem:v,
                    menuKey:v.url,
                    menuCrumbs:[...crumbsNode],
                }
            }else if("list" == type){
                map[v.url] = {
                    type:type,
                    cate:[cateSlug],
                    menu:parentNode,
                    menuItem:v,
                    menuKey:v.url,
                    menuCrumbs:[...crumbsNode],
                }
            }else if("con" == type){
                map[v.url] = {
                    type:"code",
                    code:cateSlug,
                    menu:parentNode,
                    menuItem:v,
                    menuKey:v.url,
                    menuCrumbs:crumbsNode,
                }
            }
            if(v.list?.length){
                crumbsNode.push({text:v.text,url:v.url,id:v.id});
                getResult(v.list,parentNode,crumbsNode);
            }
        })
    }
    if(!map){
        map = {};
        getResult(global.MENU);
        getUrlMap.map = map;
    }
    //
    let option = map[key];
    if(option){
        return option;
    }else{
        let code = key.replace(/.*\//,"");
        return {
            menu:{list:[]},
            code:code,
            menuKey:key
        }
    }
}
// 获取菜单栏配置
_.getUrl = function(){
    let url = _.his.location.pathname;
    return getUrlMap(url);
}
// 获取大类-映射的菜单
_.getMenu = function(cate){
    let map = getUrlMap(`/list/${cate}`);
    let menuCrumbs = map.menuCrumbs;
    if(menuCrumbs){
        menuCrumbs = [...menuCrumbs,{text:map.menuItem.text,url:map.menuItem.url}]
    }
    return {...map,menuCrumbs};
}

_.htmlStyle = function(a){
    console.log(a.replace(/style\=\"(.*?)\"/g,(a,v)=>{
        let map = {};
        v.split(/\;[\s]{0,2}/).map((k)=>{
            let a = k.split(':');
            map[_.camelCase(a[0])] = a[1];
        })
        return `style={${JSON.stringify(map)}}`
    }))
}

_.isWeixin = function(){
    let ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i)=="micromessenger") {
        return true;
    } else {
        return false;
    }
}


_.params = function(){
    let str = (window.location.search || '').replace(/\?/g,'');
    let res = {};
    str.split('&').map((v)=>{
        let arr = v.split('=');
        if(arr[0]){
            res[arr[0]] = arr[1];
        }
    })
    return res;
}

_.paramsStr = function(map){
    let arr = [];
    let mapAll = Object.assign(_.params(),map);
    Object.keys(mapAll).map((key)=>{
        let val = mapAll[key];
        if(val){
            arr.push(`${key}=${val}`)
        }
    })
    return arr.join("&");
}

_.udid = ()=>{
    return Math.random().toString('32').replace(/.*\./,'');
}

_.MOMENT = function(date){
    if(Number(date) && date?.length>11){// 特殊处理：时间戳
        date = Number(date);
    }
    //
    let m = global.moment(date);
    if(m._isValid){
        return m;
    }else{
        return {
            _d:'',
            format:function(){
                return ""
            }
        };
    }
}

// _.MONEY(1,2,'$',',')
_.MONEY = function(val,places = 2, symbol = '', thousand = '', decimal = '.'){
    let number = val/100,
        negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
}

// 汉子货币格式
_.MONEY_CURRENCY = function(money) {
    //汉字的数字
    let cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
    //基本单位
    let cnIntRadice = new Array('', '拾', '佰', '仟');
    //对应整数部分扩展单位
    let cnIntUnits = new Array('', '万', '亿', '兆');
    //对应小数部分单位
    let cnDecUnits = new Array('角', '分', '毫', '厘');
    //整数金额时后面跟的字符
    let cnInteger = '整';
    //整型完以后的单位
    let cnIntLast = '元';
    //最大处理的数字
    let maxNum = 999999999999.9999;
    //金额整数部分
    let integerNum;
    //金额小数部分
    let decimalNum;
    //输出的中文金额字符串
    let chineseStr = '';
    //分离金额后用的数组，预定义
    let parts;
    if (money == '') { return ''; }
    money = parseFloat(money);
    if (money >= maxNum) {
        //超出最大处理数字
        return '';
    }
    if (money == 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
    }
    //转换为字符串
    money = money.toString();
    if (money.indexOf('.') == -1) {
        integerNum = money;
        decimalNum = '';
    } else {
        parts = money.split('.');
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
    }
    //获取整型部分转换
    if (parseInt(integerNum, 10) > 0) {
        let zeroCount = 0;
        let IntLen = integerNum.length;
        for (let i = 0; i < IntLen; i++) {
            let n = integerNum.substr(i, 1);
            let p = IntLen - i - 1;
            let q = p / 4;
            let m = p % 4;
            if (n == '0') {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    chineseStr += cnNums[0];
                }
                //归零
                zeroCount = 0;
                chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if (m == 0 && zeroCount < 4) {
                chineseStr += cnIntUnits[q];
            }
        }
        chineseStr += cnIntLast;
    }
    //小数部分
    if (decimalNum != '') {
        let decLen = decimalNum.length;
        for (let ii = 0; ii < decLen; ii++) {
            let nn = decimalNum.substr(ii, 1);
            if (nn != '0') {
                chineseStr += cnNums[Number(nn)] + cnDecUnits[ii];
            }
        }
    }
    if (chineseStr == '') {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (decimalNum == '') {
        chineseStr += cnInteger;
    }
    return chineseStr;
}

// 设置标题
_.setDocumentTitle = function (title) {
    if(document.title == title){
        return;
    }
    //
    document.title = title;
    if (/ip(hone|od|ad)/i.test(navigator.userAgent)) {
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        iframe.style.width = '1px';
        iframe.style.height = '1px';
        // 利用iframe的onload事件刷新页面
        iframe.onload = function () {
            setTimeout(function () {
                document.body.removeChild(iframe);
            }, 0);
        };
        document.body.appendChild(iframe);
    }
}

// 设置
_.setOnce = (time,callback)=>{
    clearTimeout(_.setOnce.timer);
    _.setOnce.timer = setTimeout(()=>{
        callback();
    },time)
}

/**
 * 脱敏
 * 中文名字3：只展示姓名第一个字
 * 手机号11：前三后四不脱敏，中间脱敏
 * 身份证号18：年月日脱敏，前6后4不脱敏
 * 银行卡19：前6位和后4位不脱敏，中间脱敏
 * */
_.dataDesensitize = function(str){
    if(typeof str != "string" || str.length < 2){
        return "";
    }
    let arr = [];
    // 常规处理
    if(str.length<3){
        arr.push(str.substr(0,1));
        arr.push("*");
    }else if(str.length<4){
        arr.push(str.substr(0,1));
        arr.push("*");
        arr.push(str.substr(str.length-1));
    }else if(str.length<8){
        arr.push(str.substr(0,1));
        arr.push("***");
        arr.push(str.substr(str.length-1));
    }else if(str.length<12){
        arr.push(str.substr(0,3));
        arr.push("***");
        arr.push(str.substr(str.length-4));
    }else{
        let size = str.length/4;
        let pos = str.length%4 || 4;
        size = pos == 4?(size - 1):size;
        for(let ii=0;ii<3;ii++){
            arr.push("**** ")
        }
        arr.push(str.substr(str.length-4));
    }
    return arr.join("");
}

/*
* 脱敏-自定义
* 主要处理银行卡 17-23位
* */
_.dataDesensitizeCard = function(str,split = "$1",pos = 4){
    // TYPE
    let fixPos = str.length%pos || pos;// 修正位置
    return str.replace(RegExp(`(\\d{${pos}})(\\d*)(\\d{${fixPos}})`),(s,firstFix,preFix,lastFix)=>{
        return firstFix +'  '+ preFix.replace(/(\d{4})/g,"$1 ").replace(/(\d)/g,split) +'  '+ lastFix;
    })
}

// 获取菜单栏配置
_.go = function(url){
    if(url.indexOf('http')>-1){
        window.open(url,'_blank');
    }else{
        return _.his.push(url);
    }
}
